package ru.nsu.expertsystem.chucknorris;

import java.lang.reflect.Field;

public class Object {
	private final String name;

	public Object(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	@Override
	public final int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public final boolean equals(java.lang.Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Object other = (Object) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	public static <T extends Object> T getConstantByName(Class<T> clazz, String name) throws SecurityException, NoSuchFieldException {
		if(clazz == null || name == null)
			throw new IllegalArgumentException("null");
		final Field [] fields = clazz.getFields();
		for(Field field : fields) {
			final java.lang.Object fieldValue;
			try {
				fieldValue = field.get(null);
			} catch (Exception e) {
				continue;
			}
			if(fieldValue == null || fieldValue.getClass().getSuperclass() != clazz)
				continue;
			final T constant = (T)fieldValue;
			if(constant.getName() != null && constant.getName().equals(name))
				return constant;
			
		}
		return null;
	}
	
}
